<template>
  <div class="createPost-main-container-signed">
    <div v-show="value == '5'">
      <el-divider
        style="margin: 20px"
      ><span
        style="color: #666; font-size: 12px"
      >以下为当前签约详细信息</span></el-divider>
      <el-form
        ref="submitFrom"
        :model="submitFrom"
        label-position="right"
        class="form-container"
      >
        <el-form-item
          style="margin-bottom: 10px; margin-top: 30px"
          label-width="120px"
          label="签约描述:"
        >
          <el-input
            v-model="submitFrom.signing_describe"
            :rows="1"
            type="textarea"
            autosize
            placeholder="签约过程中甲方的特殊要求,或无"
          />
        </el-form-item>

        <el-form-item
          style="margin-bottom: 10px"
          label-width="120px"
          label="上传合同扫描件:"
        >
          <el-button
            type="default"
            size="small"
            @click="uploadFile"
          ><span>上传文件</span></el-button>
        </el-form-item>

        <el-form-item style="margin-bottom: 10px" label-width="120px" label="">
          <viewer
            ref="viewer"
            :images="images"
            class="viewer"
            style="width: 100px; boder: 1px solid red; display: none"
            @inited="inited"
          >
            <img
              v-for="(src, index) in images"
              :key="index"
              :src="src"
              class="image"
            >
          </viewer>
          <div class="container">
            <div
              v-for="(item, index) in file_list"
              :key="index"
              class="box"
              :class="item.active == 1 ? 'active' : ''"
              @click="changeBg(index)"
              @dblclick="dbClick(item.name, index)"
            >
              <div class="iconBox">
                <div class="btnDelete" @click="deleteFile(index)" />
                <img width="80" height="80" :src="item.urls" alt="">
              </div>
              <div class="fileText">
                <span
                  :title="item.name"
                  style="
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    width: 100%;
                    overflow: hidden;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2;
                    display: -webkit-box;
                  "
                >{{ item.name }}</span>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-dialog
          title="上传文件"
          :close-on-click-modal="false"
          :visible.sync="uploadFileDialog"
          width="500px"
        >
          <el-upload
            ref="upload"
            class="upload-input"
            drag
            :action="uploadAction"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :on-success="getFilePath"
            :on-change="handleChangeFile"
            :headers="headers"
            :accept="limit_file_type.toString()"
            :limit="3"
            :auto-upload="false"
          >
            <!-- multiple -->
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击选择文件</em>
            </div>
            <div slot="tip" class="el-upload__tip">
              只能上传<span style="color: red">{{
                limit_file_type.join("/").replace(/\./g, "")
              }}</span>文件，且单个文件不超过50MB
            </div>
          </el-upload>

          <span slot="footer" class="dialog-footer">
            <el-button @click="cancelUpload">取 消</el-button>
            <!-- <el-button type="primary" @click="confirmUpload">确 定</el-button> -->
            <el-button type="primary" @click="submitUpload">上 传</el-button>
          </span>
        </el-dialog>
      </el-form>

      <div
        class="footer"
        style="width: 100%; text-align: center; padding: 10px"
      >
        <el-button
          style="margin-left: 10px; border: 1px silid red"
          type="success"
          @click="submit"
        >提交</el-button>
        <router-link :to="'/project/index'">
          <el-button
            style="margin-left: 30px"
            size="medium"
            type="default"
          >返回</el-button>
        </router-link>
      </div>
    </div>

    <div v-show="displayForm" class="createPost-main-container-signed">
      <el-divider
        style="margin: 20px"
      ><span
        style="color: #666; font-size: 12px"
      >以下为当前签约详细信息</span></el-divider>
      <el-form
        ref="submitFrom"
        :model="submitFrom"
        label-position="right"
        class="form-container"
      >
        <el-form-item
          style="margin-bottom: 10px"
          label-width="120px"
          label="签约描述:"
        >
          <el-input
            v-model="submitFrom.signing_describe"
            :rows="1"
            :disabled="true"
            type="textarea"
            autosize
            placeholder="无"
          />
        </el-form-item>

        <el-form-item
          style="margin-bottom: 10px"
          label-width="120px"
          label="合同扫描件下载:"
        >
          <div class="container">
            <div
              v-for="(item, index) in file_list"
              :key="index"
              class="box"
              :class="item.active == 1 ? 'active' : ''"
              @click="changeBg(index)"
              @dblclick="dbClick(item.name, index)"
            >
              <div class="iconBox">
                <img width="80" height="80" :src="item.urls" alt="">
              </div>
              <div class="fileText">
                <span
                  :title="item.name"
                  style="
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    width: 100%;
                    overflow: hidden;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2;
                    display: -webkit-box;
                  "
                  @click="downLoad(item.url, item.name)"
                >{{ item.name }}</span>
              </div>
            </div>
          </div>
          <span
            style="width: 100%; text-align: center; color: #ccc"
          >(点击文件名下载)</span>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getProjectDetail, insertFile, insertSigningInfo } from '@/api/project'
import { getToken } from '@/utils/auth'
import { getInfo } from '@/api/user'
import { analysisExcel } from '@/api/folder'
// 需要的表单
const formSubmit = {
  signing_describe: '', // 签约描述
  file_path: [] // 附件数组
}
// http://dc.tuobao.m.com/storage/images
export default {
  props: {
    is_signed: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      id: '', // 当前项目的id
      submitFrom: Object.assign({}, formSubmit),
      username: '',
      value: '',
      file_new_names: {},
      uploadFileDialog: false,
      displayForm: false,
      images: [],
      file_list: [],
      fileLists: [],
      file_types: {
        docx: ['doc', 'docx'],
        xlsx: ['xls', 'xlsx'],
        ppt: ['ppt', 'pptx'],
        jpg: ['jpg', 'jpeg'],
        zip: ['zip', 'rar'],
        txt: ['txt', 'text'],
        mpge: ['mp3', 'mp4'],
        pdf: ['pdf'],
        png: ['png'],
        folder: ['folder']
      },
      options: [
        {
          value: '监理',
          label: '监理'
        },
        {
          value: '造价咨询',
          label: '造价咨询'
        },
        {
          value: '代理',
          label: '代理'
        },
        {
          value: '全过程咨询',
          label: '全过程咨询'
        }
      ],
      // 添加头部请求
      headers: {
        Authorization: 'Bearer ' + getToken(),
        post: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      },
      uploadAction: '/adminapi/project/insertFile'
    }
  },
  computed: {
    // 计算属性的 getter
    limit_file_type: function() {
      const limit_file_type = []
      for (const i in this.file_types) {
        this.file_types[i].forEach((_type) => {
          if (_type != 'folder') {
            limit_file_type.push('.' + _type)
          }
        })
      }

      // `this` 指向 vm 实例
      return limit_file_type
    }
  },

  created() {
    if (this.is_signed) {
      const value = this.$route.query.value
      const id = this.$route.query && this.$route.query.id
      this.value = value
      // if (value == "1" || value =="10") {
      this.getProjectData(id)
      // }
      this.id = id
      this.getUserInfo()
    }
  },
  methods: {
    // 删除文件
    deleteFile(index) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButton: '取消',
        type: 'warning'
      })
        .then(() => {
          this.file_list.splice(index, 1)
        })
        .catch(() => {})
    },
    // 鼠标选中文件改变背景颜色
    changeBg(index) {
      let num
      for (let i = 0; i < this.file_list.length; i++) {
        if (i === index) {
          num = i
        } else {
          this.file_list[i].active = 0
        }
      }
      this.file_list[num].active = 1
    },
    // 双击事件
    dbClick(fileName, index) {
      if (
        this.file_list[index].fileType == 'png' ||
        this.file_list[index].fileType == 'jpg' ||
        this.file_list[index].fileType == 'jpeg'
      ) {
        const arr = []
        arr.push(this.file_list[index].url)
        this.images = arr
        this.$viewer.view(0)
      } else {
        this.$message({
          type: 'info',
          message: '当前类型文件不支持预览!'
        })
      }
    },
    cancelUpload() {
      this.uploadFileDialog = false
    },
    // 上传方法
    uploadFile() {
      this.uploadFileDialog = true
      this.file_new_names = {}
      this.fileLists = []
    },
    // 下载文件
    downLoad(url, name) {
      this.$notify({
        title: '开始下载',
        duration: 2000
      })
      const x = new XMLHttpRequest()
      x.open('GET', url, true)
      x.responseType = 'blob'
      x.onload = function() {
        const url = window.URL.createObjectURL(x.response)
        const a = document.createElement('a')
        a.href = url
        a.download = name
        a.click()
      }
      x.send()
    },
    inited(viewer) {
      this.$viewer = viewer
    },
    submitUpload() {
      this.$refs.upload.submit()
      this.uploadFileDialog = false
    },
    // 获取文件返回路径 需要先上传 上传成功后返回路径再保存到数据库
    getFilePath(res) {
      if (res.data != null) {
        if (
          res.data.fileType == 'png' ||
          res.data.fileType == 'jpeg' ||
          res.data.fileType == 'jpg'
        ) {
          this.file_list.push({
            name: res.data.name,
            url: res.data.url,
            urls: res.data.url,
            fileType: res.data.fileType
          })
        } else {
          this.file_list.push({
            name: res.data.name,
            url: res.data.url,
            urls: this.getIconUrl(res.data.fileType),
            fileType: res.data.fileType
          })
        }
        this.$message({
          type: 'success',
          message: '上传成功!'
        })
      }
    },
    // 根据返回的数据类型显示不同的图片
    getIconUrl(type) {
      const types_icon_arr = this.file_types
      let show_tyupe = 'none'
      for (const i in types_icon_arr) {
        types_icon_arr[i].forEach((_type) => {
          if (type == _type) {
            show_tyupe = i
          }
        })
      }
      return require('@/assets/resourse/' + show_tyupe + '.png')
    },
    // 提交签约信息
    submit() {
      this.submitFrom.file_path = this.file_list
      new Promise((resolve, reject) => {
        insertSigningInfo({
          id: this.id,
          submitFrom: this.submitFrom,
          username: this.username
        }).then(() => {
          this.$message({
            type: 'success',
            message: '签约信息填写成功!'
          })
          this.$router.push('/project/index')
        })
      })
    },
    // 获取项目
    getProjectData(id) {
      new Promise((reslove, reject) => {
        getProjectDetail({ id: id }).then((response) => {
          this.submitFrom = response.data
          if (response.data.signing_describe != null) {
            if (
              response.data.project_status != 12 && response.data.project_status != 4
            ) {
              this.displayForm = true
            }
          }
          for (let i = 0; i < this.submitFrom.file_path.length; i++) {
            if (this.submitFrom.file_path[i].type == '1') {
              if (
                this.submitFrom.file_path[i].fileType == 'png' ||
                this.submitFrom.file_path[i].fileType == 'jpeg' ||
                this.submitFrom.file_path[i].fileType == 'jpg'
              ) {
                this.file_list.push({
                  name: this.submitFrom.file_path[i].file_name,
                  url: this.submitFrom.file_path[i].file_path,
                  urls: this.submitFrom.file_path[i].file_path,
                  fileType: this.submitFrom.file_path[i].fileType
                })
              } else {
                this.file_list.push({
                  name: this.submitFrom.file_path[i].file_name,
                  url: this.submitFrom.file_path[i].file_path,
                  urls: this.getIconUrl(this.submitFrom.file_path[i].fileType),
                  fileType: this.submitFrom.file_path[i].fileType
                })
              }
            }
          }
          // console.log(this.file_list);
        })
      })
    },
    // 选择文件发生变化钩子
    handleChangeFile() {
      this.fileLists = this.$refs.upload.$children[0].fileList
    },
    // 文件移除
    handleRemove(file, fileList) {
      // console.log(this.submitFrom.file_path);
      // 删除暂存在需要保存到数据库数组中的数据
      for (let i = 0; i < this.submitFrom.file_path.length; i++) {
        if (this.submitFrom.file_path[i].name == file.name) {
          this.submitFrom.file_path.splice(i, 1)
          return
        }
      }
    },
    // 上传前文件类型判断
    beforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      let is_overflow = 1

      this.limit_file_type.forEach((item, index) => {
        if (item == '.' + testmsg) {
          is_overflow = 0
        }
      })
      if (is_overflow) {
        this.$message({
          message:
            '上传文件只能是 ' +
            this.limit_file_type.toString().replace(/\./g, '') +
            '格式!',
          type: 'error'
        })
      }

      return !is_overflow
    },
    // 文件限制
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    // 文件移除前
    beforeRemove(file, fileList) {
      // console.log(this.submitFrom.file_path);
      // console.log(file);
      // console.log(fileList);
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 获取当前用户的登录信息
    getUserInfo() {
      new Promise((resolve, reject) => {
        getInfo().then((response) => {
          // console.log("info");
          // console.log(response.data);
          this.username = response.data.name // 当前登录用户的姓名
        })
      })
    }
  }
}
</script>
<style>
.createPost-main-container-signed {
  padding: 0px 45px 0px 50px;
}
.createPost-main-container-signed .el-form-item--medium .el-form-item__content {
  line-height: 25px;
}
.createPost-main-container-signed .el-form-item--medium .el-form-item__label {
  line-height: 25px;
}
.createPost-main-container-signed .container {
  /* width: 100%; */
  /* margin: 10px; */
  /* border: 1px solid red; */
  display: grid;
  grid-row-gap: 20px;
  grid-column-gap: 20px;
  grid-template-columns: repeat(auto-fill, 100px);
  /* grid-template-rows: repeat(auto-fill, 100px); */
}

.createPost-main-container-signed .container .box {
  /* border: 1px solid red; */
  width: 112px;
  height: 136px;
  /* margin: 5px; */
  padding: 10%;
}

.createPost-main-container-signed .container .box .iconBox {
  width: 100%;
  height: 80px;
  text-align: center;
  position: relative;
}
.createPost-main-container-signed .container .box .iconBox .btnDelete {
  width: 14px;
  height: 14px;
  background: rgb(146, 145, 145);
  border: 0px none;
  /* border-radius: 1px; */
  position: absolute;
  float: right;
  text-align: center;
  line-height: 14px;
  top: 0px;
  right: 0px;
  display: block;
}
.createPost-main-container-signed .container .box .iconBox .btnDelete::after {
  content: "X";
  font-size: 16px;
  color: #fff;
  /* border: 1px solid red; */
}

.createPost-main-container-signed .container .box .fileText {
  width: 100%;
  margin-top: 10px;
  text-align: center;
  height: 23px;
  line-height: 23px;
  color: #595c5f;
  font-size: 15px;
}
.createPost-main-container-signed .active {
  background: #eff3f9 none repeat scroll 0 0;
  border-color: #bcccde;
  border-radius: 10px;
}
.createPost-main-container-signed .el-textarea.is-disabled .el-textarea__inner {
  background: #fff;
  color: #000;
  border: none;
  padding: 0px 0px;
  resize: none;
}
</style>
